import os
import sys
from datetime import datetime
from core.detectidentify.web.report_generator import ReportGenerator as WebReportGenerator
from core.detectidentify.web.config_adapter import ConfigAdapter
from core.detectidentify.mysql.main import MySQLFullAnalyzer
import yaml

class DetectionService:
    def __init__(self):
        # 初始化配置
        self.config = self._load_config()
    
    def _load_config(self):
        """加载配置文件"""
        config_path = os.path.join(os.path.dirname(__file__), '..', 'core', 'detectidentify', 'web', 'config.yaml')
        with open(config_path, 'r', encoding='utf-8') as f:
            return yaml.safe_load(f)
    
    def run_web_detection(self):
        """运行web识别检测"""
        try:
            # 使用新的配置适配器
            config_adapter = ConfigAdapter()
            
            # 验证配置
            if not config_adapter.validate_config():
                return {
                    "success": False,
                    "message": "配置验证失败，请检查config.json文件",
                    "report_path": None,
                    "report_name": None
                }
            
            # 获取API配置
            api_key = config_adapter.get_api_key()
            api_url = config_adapter.get_api_url()
            model_name = config_adapter.get_model()
            
            # 创建报告生成器
            report_generator = WebReportGenerator(api_key, api_url, model_name, config_adapter)
            
            # 生成完整报告
            report_path = report_generator.generate_full_report()
            
            # 返回报告路径
            return {
                "success": True,
                "message": "web识别检测完成",
                "report_path": report_path,
                "report_name": os.path.basename(report_path)
            }
        except Exception as e:
            return {
                "success": False,
                "message": f"web识别检测失败: {str(e)}",
                "report_path": None,
                "report_name": None
            }
    
    def run_mysql_detection(self):
        """运行mysql识别检测"""
        try:
            # MySQL数据库配置
            db_config = {
                "host": "127.0.0.1",
                "user": "root",
                "password": "root",  # 在实际应用中，应该从安全的地方获取
                "port": 3306
            }
            
            # 创建分析器
            analyzer = MySQLFullAnalyzer(db_config)
            
            # 执行分析流程
            analyzer.run_full_analysis(metrics_duration=1)
            
            # 生成报告文件路径
            output_dir = "data/DefectIdentification_data/mysql_data"
            os.makedirs(output_dir, exist_ok=True)
            
            # 生成报告
            analyzer.generate_report(output_dir)
            
            # 查找生成的报告文件
            report_files = [f for f in os.listdir(output_dir) if f.startswith("mysql_optimization_report") and f.endswith(".md")]
            
            if report_files:
                latest_report = max(report_files, key=lambda x: os.path.getctime(os.path.join(output_dir, x)))
                report_path = os.path.join(output_dir, latest_report)
                
                return {
                    "success": True,
                    "message": "mysql识别检测完成",
                    "report_path": report_path,
                    "report_name": latest_report
                }
            else:
                return {
                    "success": False,
                    "message": "未找到生成的mysql报告文件",
                    "report_path": None,
                    "report_name": None
                }
        except Exception as e:
            return {
                "success": False,
                "message": f"mysql识别检测失败: {str(e)}",
                "report_path": None,
                "report_name": None
            }
    
    def get_mysql_reports(self):
        """获取MySQL报告文件列表"""
        try:
            mysql_data_dir = "data/DefectIdentification_data/mysql_data"
            if os.path.exists(mysql_data_dir):
                files = [f for f in os.listdir(mysql_data_dir) if os.path.isfile(os.path.join(mysql_data_dir, f))]
                return {
                    "success": True,
                    "files": files
                }
            else:
                # 创建目录如果不存在
                os.makedirs(mysql_data_dir, exist_ok=True)
                return {
                    "success": True,
                    "files": []
                }
        except Exception as e:
            return {
                "success": False,
                "message": f"获取MySQL报告列表失败: {str(e)}",
                "files": []
            }

    def get_web_reports(self):
        """获取Web报告文件列表"""
        try:
            web_data_dir = "data/DefectIdentification_data/web_data"
            if os.path.exists(web_data_dir):
                files = [f for f in os.listdir(web_data_dir) if os.path.isfile(os.path.join(web_data_dir, f))]
                return {
                    "success": True,
                    "files": files
                }
            else:
                # 创建目录如果不存在
                os.makedirs(web_data_dir, exist_ok=True)
                return {
                    "success": True,
                    "files": []
                }
        except Exception as e:
            return {
                "success": False,
                "message": f"获取Web报告列表失败: {str(e)}",
                "files": []
            }
    
    def get_mysql_report_content(self, filename):
        """获取MySQL报告文件内容"""
        try:
            mysql_data_dir = "data/DefectIdentification_data/mysql_data"
            file_path = os.path.join(mysql_data_dir, filename)
            
            # 检查文件是否存在
            if os.path.exists(file_path) and os.path.isfile(file_path):
                with open(file_path, 'r', encoding='utf-8') as f:
                    content = f.read()
                    return {
                        "success": True,
                        "content": content
                    }
            else:
                return {
                    "success": False,
                    "message": "文件未找到"
                }
        except Exception as e:
            print(f"读取MySQL报告文件失败: {str(e)}")
            return {
                "success": False,
                "message": f"读取文件失败: {str(e)}"
            }
    
    def get_web_report_content(self, filename):
        """获取Web报告文件内容"""
        try:
            web_data_dir = "data/DefectIdentification_data/web_data"
            file_path = os.path.join(web_data_dir, filename)
            
            # 检查文件是否存在
            if os.path.exists(file_path) and os.path.isfile(file_path):
                with open(file_path, 'r', encoding='utf-8') as f:
                    content = f.read()
                    return {
                        "success": True,
                        "content": content
                    }
            else:
                return {
                    "success": False,
                    "message": "文件未找到"
                }
        except Exception as e:
            print(f"读取Web报告文件失败: {str(e)}")
            return {
                "success": False,
                "message": f"读取文件失败: {str(e)}"
            }

# 单例模式
detection_service = DetectionService()